﻿namespace LeetCodeProject._0001_1000._001_100._21_30._21;

public class Solution
{
    public ListNode MergeTwoLists(ListNode list1, ListNode list2)
    {
        var dummy = new ListNode();
        var tail = dummy;
        var node1 = list1;
        var node2 = list2;
        while (list1 != null && list2 != null)
        {
            var n1 = list1.val;
            var n2 = list2.val;
            if (n1 <= n2)
            {
                tail = tail.next = list1;
                list1 = list1.next;
            }
            else
            {
                tail = tail.next = list2;
                list2 = list2.next;
            }
        }

        var nodes = list1 ?? list2;
        while (nodes != null)
        {
            tail = tail.next = nodes;
            nodes = nodes.next;
        }

        return dummy.next;
    }


    // 方法二：迭代
    public ListNode MergeTwoLists2(ListNode l1, ListNode l2)
    {
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null)
        {
            if (l1.val <= l2.val)
            {
                prev.next = l1;
                l1 = l1.next;
            }
            else
            {
                prev.next = l2;
                l2 = l2.next;
            }

            prev = prev.next;
        }

        // 合并后l1和l2最多只有一个还未被合并完，直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;
    }
}

public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}